package com.jgsu.farm.exception;

import com.jgsu.farm.utils.CommonResult;
import com.jgsu.farm.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: farm-10-14-2019
 * @description: 定义全局异常处理
 * @author: Mr.zuo
 * @create: 2019-12-05 17:25
 **/
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHander {

    @ExceptionHandler(value = Exception.class)
    public CommonResult handlerException(Exception e){
        if (e instanceof DataAddException){
            log.error("【全局异常拦截】DataAddException: 请求方法 {}, 请求路径 {}",((DataAddException)e).getCode(),((DataAddException)e).getMessage());
            return CommonResult.failed(ResultCode.DATA_ADD_ERROR);
        }else if (e instanceof DataNotExistException){
            log.error("【全局异常拦截】DataNotExistException: 请求方法 {}, 请求路径 {}",((DataNotExistException)e).getCode(),((DataNotExistException)e).getMessage());
            return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
        }else if (e instanceof FileException){
            log.error("【全局异常拦截】FileException: 请求方法 {}, 请求路径 {}",((FileException)e).getCode(),((FileException)e).getMessage());
            return CommonResult.failed(ResultCode.FILE_ERROR);
        }else if (e instanceof ImageException){
            log.error("【全局异常拦截】ImageException: 请求方法 {}, 请求路径 {}",((ImageException)e).getCode(),((ImageException)e).getMessage());
            return CommonResult.failed(ResultCode.IMAGE_ERROR);
        }else if (e instanceof DataMatchException){
            log.error("【全局异常拦截】DataMatchException: 请求方法 {}, 请求路径 {}",((DataMatchException)e).getCode(),((DataMatchException)e).getMessage());
            return CommonResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        } else {
            log.error("服务器内部出错{}",e);
            return CommonResult.failed(ResultCode.FAILED);
        }
    }
}
